import Vue from 'vue'
import VueRouter from 'vue-router'

import store from '@/store'
//判断是否有权限，有就next，没有就返回
function hasUrl(url, next) {
  let result = store.getters.getUser.menus_url.some(item => item == url)
  if (result) {
    next()
  } else {
    next('/home')
  }
}

Vue.use(VueRouter)
export const routerIndex = [{
    path: '/menu',
    component: () => import('../views/menu/menu.vue'),
    meta: {
      title: '菜单管理'
    },
    beforeEnter(to, from, next) {
      hasUrl('/menu', next)
    }
  },
  {
    path: '/role',
    component: () => import('../views/role/role.vue'),
    meta: {
      title: '角色管理'
    },
    beforeEnter(to, from, next) {
      hasUrl('/role', next)
    }
  },
  {
    path: '/admin',
    component: () => import('../views/admin/admin.vue'),
    meta: {
      title: '管理员管理'
    },
    beforeEnter(to, from, next) {
      hasUrl('/admin', next)
    }
  },
  {
    path: "/cate",
    component: () => import("../views/cate/cate.vue"),
    meta: {
      title: "商品分类管理",
    },
    beforeEnter(to, from, next) {
      hasUrl('/cate', next)
    }
  },
  {
    path: "/specs",
    component: () => import("../views/specs/specs.vue"),
    meta: {
      title: "商品规格管理",
    },
    beforeEnter(to, from, next) {
      hasUrl('/specs', next)
    }
  },
  {
    path: "/goods",
    component: () => import("../views/goods/goods.vue"),
    meta: {
      title: "商品管理",
    },
    beforeEnter(to, from, next) {
      hasUrl('/goods', next)
    }
  },
  {
    path: "/member",
    component: () => import("../views/member/member.vue"),
    meta: {
      title: "会员管理",
    },
    beforeEnter(to, from, next) {
      hasUrl('/member', next)
    }
  },
  {
    path: "/banner",
    component: () => import("../views/banner/banner.vue"),
    meta: {
      title: "轮播图管理",
    },
    beforeEnter(to, from, next) {
      hasUrl('/banner', next)
    }
  },
  {
    path: "/seck",
    component: () => import("../views/seck/seck.vue"),
    meta: {
      title: "限时秒杀管理",
    },
    beforeEnter(to, from, next) {
      hasUrl('/seck', next)
    }
  },
]
const routes = [{
    path: '/login',
    component: () => import('../pages/login.vue')
  },
  {
    path: '/index',
    component: () => import('../pages/index.vue'),
    children: [{
        path: '/home',
        component: () => import('../views/home.vue')
      },
      ...routerIndex,
      {
        path: '',
        redirect: '/home'
      }
    ]
  }, {
    path: '*',
    redirect: '/index'
  }
]

const router = new VueRouter({
  // mode: 'history',
  // base: process.env.BASE_URL,
  routes
})
//调用全局前置守卫
router.beforeEach((to,from,next)=>{
  if (to.path == '/login') {
    next();
    return
  }
  //如果已经登陆就放行
  if (store.getters.getUser) {
    next();
    return
  }
  //以上都不符合跳转登录页
  next('/login')
})

export default router